package com.test.springtp.controller;


import ch.qos.logback.classic.spi.STEUtil;
import com.test.springtp.model.File;
import com.test.springtp.model.Product;
import com.test.springtp.model.ProductVo;
import com.test.springtp.service.IFileService;
import com.test.springtp.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ll
 * @since 2025-10-31
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;
    @Autowired
    private IFileService fileService;
    @RequestMapping("/listt")
    private String queryAll(ProductVo productVo, Model model) {
        List<ProductVo> productVos = productService.queryAll(productVo);
        for (ProductVo vo : productVos) {
            System.out.println(vo);
        }
        System.out.println("http://localhost:8081/tp/product/listt");
        model.addAttribute("productVo", productVos);
        return "index";
    }
    @RequestMapping("/upload")
    public String toUpload(Model model,Integer productId) {
        model.addAttribute("id", productId);
        return "imgUpload";
    }

    @RequestMapping("/toUpload")
    public String upload(MultipartFile fname, Product product) {
        String oFilename = fname.getOriginalFilename();
        String contentType = fname.getContentType();
        String url="D:\\java\\springtp\\src\\main\\resources\\static\\img\\"+oFilename;
        Long fileId=System.currentTimeMillis();
        File file=new File();
        file.setFileId(fileId);
        file.setRealName(oFilename);
        file.setContentType(contentType);
        file.setUrl(url);

        java.io.File f=new java.io.File(url);



        try {
            fname.transferTo(f);
            boolean save = fileService.save(file);
            product.setProductImage(fileId+"");


            if (save){
                boolean update = productService.updateById(product);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "redirect:listt";
    }
    @RequestMapping("/del")
    public String dell(Long productId){
        boolean b = productService.removeById(productId);
        return "redirect:listt";
    }

    @RequestMapping("/update")
    public String update(ProductVo productVo, Model model) {
        return queryAll(productVo,model);
    }
}
